package com.abc.recycling.controller;

import com.abc.recycling.model.User;
import com.abc.recycling.model.Order;
import com.abc.recycling.service.UserService;
import com.abc.recycling.service.OrderService;
import com.abc.recycling.service.MessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Controller
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final OrderService orderService;
    private final MessageService messageService;

    @GetMapping("/user")
    public String userHome(Model model) {
        try {
            log.info("访问用户首页");
            // 获取当前用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            log.debug("当前用户: {}", username);
            
            // 获取用户信息
            User user = userService.getUserByUsername(username);
            model.addAttribute("user", user);
            
            // 获取最近订单
            List<Order> recentOrders = orderService.findRecentOrdersByUser(user.getId());
            model.addAttribute("recentOrders", recentOrders);
            
            // 获取未读消息数
            int unreadMessages = messageService.countUnreadMessages(user.getId());
            model.addAttribute("unreadMessages", unreadMessages);
            
            // 获取用户订单统计信息
            Long totalOrders = orderService.countOrdersByUser(user.getId());
            BigDecimal totalWeight = orderService.getTotalWeightByUser(user.getId());
            Double averageRating = orderService.getAverageRatingByUser(user.getId());
            
            model.addAttribute("totalOrders", totalOrders);
            model.addAttribute("totalWeight", totalWeight.doubleValue());
            model.addAttribute("averageRating", averageRating);
            
            log.info("用户首页数据加载完成");
            return "resident/index";
        } catch (Exception e) {
            log.error("访问用户首页失败: {}", e.getMessage());
            throw e;
        }
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    @PostMapping("/register")
    @ResponseBody
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            User registeredUser = userService.register(user);
            return ResponseEntity.ok(registeredUser);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/profile/password")
    @ResponseBody
    public ResponseEntity<?> changePassword(
            @RequestParam Long userId,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
        try {
            userService.changePassword(userId, oldPassword, newPassword);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/admin/users/{role}")
    public String userList(@PathVariable String role, Model model) {
        List<User> users = userService.getUsersByRole(role);
        model.addAttribute("users", users);
        model.addAttribute("role", role);
        return "admin/users";
    }

    @GetMapping("/admin/users/search")
    @ResponseBody
    public ResponseEntity<List<User>> searchUsers(
            @RequestParam String role,
            @RequestParam String keyword) {
        return ResponseEntity.ok(userService.searchUsers(role, keyword));
    }

    @PostMapping("/admin/users/{userId}/status")
    @ResponseBody
    public ResponseEntity<?> updateUserStatus(
            @PathVariable Long userId,
            @RequestParam Integer status) {
        try {
            userService.updateUserStatus(userId, status);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @DeleteMapping("/admin/users/{userId}")
    @ResponseBody
    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
        try {
            userService.deleteUser(userId);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
} 